<template>
  <view class="container">
    <!-- 头部：年份月份 -->
    <view class="calendar-header">
      <text>{{ year }}年{{ month }}月</text>
    </view>
    <!-- 全局签到按钮 -->
    <view class="global-sign-btn" @click="handleSign(now.getDate())">
      签到
    </view>
    <!-- 星期标题 -->
    <view class="calendar-week">
      <text>日</text>
      <text>一</text>
      <text>二</text>
      <text>三</text>
      <text>四</text>
      <text>五</text>
      <text>六</text>
    </view>

    <!-- 日历主体 -->
    <view class="calendar-body">
      <view
          v-for="(day, index) in calendarDays"
          :key="index"
          :class="{
          'signed': isDaySigned(day),
          'today': isToday(day),
          'empty': !day
        }"
          @click="handleSign(day)"
      >
        <text>{{ day }}</text>
        <!-- 签到按钮（仅当天且未签到时显示） -->
        <view v-if="isToday(day) && !isDaySigned(day)" class="sign-btn">
          签到
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, onMounted} from 'vue';
// 导入API工具类
import {signUserIn, getSignedStatusByMonth, getTotalSignCount} from '@/apis/userSignAPI';

// 响应式数据
const now = new Date();
// 当前年份
const year = ref(now.getFullYear());
// 当前月份
const month = ref(now.getMonth() + 1);
// 用户ID，实际项目中从登录信息获取
const userId = ref(1);

// 签到状态数组（后端返回的布尔数组）
const signStatusArray = ref([]);
// 日历日期数组
const calendarDays = ref([]);

// 核心逻辑

/**
 * 生成当月日历
 * @returns 包含当月日期及月初空白占位的数组
 */
const generateCalendar = () => {
  const firstDay = new Date(year.value, month.value - 1, 1);
  const firstDayOfWeek = firstDay.getDay();
  const daysInMonth = new Date(year.value, month.value, 0).getDate();

  const days = [];
  // 填充月初空白
  for (let i = 0; i < firstDayOfWeek; i++) {
    days.push(null);
  }
  // 填充当月日期
  for (let i = 1; i <= daysInMonth; i++) {
    days.push(i);
  }
  return days;
};

/**
 * 判断某天是否已签到
 * @param day 日期
 * @returns 是否已签到
 */
const isDaySigned = (day) => {
  if (!day) return false;
  const index = day - 1; // 日期转索引（1号 → 0）
  // 确保数组有效且索引不越界
  return signStatusArray.value.length > index && signStatusArray.value[index] === true;
};

/**
 * 判断某天是否是今天
 * @param day 日期
 * @returns 是否是今天
 */
const isToday = (day) => {
  return (
      day !== null &&
      now.getDate() === day &&
      now.getMonth() + 1 === month.value &&
      now.getFullYear() === year.value
  );
};

// 接口交互

/**
 * 获取当月签到状态
 */
const fetchSignStatus = async () => {
  try {
    // 使用API工具类，传递正确参数
    const response = await getSignedStatusByMonth(userId.value, year.value, month.value);
    console.log('获取签到状态成功:', userId.value, year.value, month.value, response);
    // 后端响应格式：{code:200, msg:"ok", data: [...]}
    if (response.data.code === 200) {
      signStatusArray.value = response.data.data || [];
    } else {
      console.error('获取签到数据失败:', response);
      uni.showToast({title: '获取签到数据失败', icon: 'none'});
    }
  } catch (error) {
    console.error('获取签到状态失败:', error);
    uni.showToast({title: '网络错误', icon: 'none'});
  }
};

/**
 * 获取本月签到总次数
 */
const fetchTotalSignCount = async () => {
  try {
    const response = await getTotalSignCount(userId.value, year.value, month.value);
    if (response.data.code === 200) {
      const userInfoStorage = uni.getStorageSync('userInfo');
      if (userInfoStorage) {
        userInfoStorage.signCount = response.data.data;
        uni.setStorageSync('userInfo', userInfoStorage);
      }
    } else {
      console.error('获取本月签到总次数失败:', response);
    }
  } catch (error) {
    console.error('获取本月签到总次数失败:', error);
  }
};

/**
 * 刷新页面数据
 */
const refreshPage = () => {
  calendarDays.value = generateCalendar();
  fetchSignStatus();
  fetchTotalSignCount();
};

/**
 * 执行当天签到
 * @param day 日期
 */
const handleSign = async (day) => {
  if (!day || !isToday(day)) return; // 非当天不处理

  if (isDaySigned(day)) {
    uni.showToast({title: '今天已签到', icon: 'none'});
    return;
  }

  try {
    // 使用API工具类调用签到接口
    const response = await signUserIn(userId.value);
    if (response.code === 200) {
      uni.showToast({title: '签到成功', icon: 'success'});
      // 刷新页面数据
      await refreshPage();
    } else {
      console.error('签到失败:', response);
      uni.showToast({title: '签到失败', icon: 'none'});
    }
  } catch (error) {
    console.error('签到失败:', error);
    uni.showToast({title: '网络错误', icon: 'none'});
  }
};

// 初始化
onMounted(() => {
  refreshPage(); // 初始化时加载数据
});
</script>

<style scoped lang="scss">
/* 样式保持不变 */
.container {
  padding: 20rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.calendar-header {
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  margin: 20rpx 0;
  color: #333;
}

/* 全局签到按钮样式 */
.global-sign-btn {
  text-align: center;
  font-size: 28rpx;
  background-color: #007aff;
  color: white;
  padding: 10rpx 0;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
}

.calendar-week {
  display: flex;
  justify-content: space-around;
  padding: 10rpx 0;
  background-color: #fff;
  border-radius: 8rpx;
  margin-bottom: 10rpx;

  text {
    font-size: 26rpx;
    color: #666;
    flex: 1;
    text-align: center;
  }
}

.calendar-body {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10rpx;

  view {
    background-color: #fff;
    border-radius: 8rpx;
    padding: 15rpx 0;
    text-align: center;
    position: relative;

    text {
      font-size: 28rpx;
      color: #333;
    }

    &.empty {
      background-color: transparent;
    }

    &.signed {
      background-color: #eaffea;
      color: #00C853;
      font-weight: bold;

      &::after {
        content: '✓';
        display: block;
        font-size: 20rpx;
        color: #00C853;
        margin-top: 5rpx;
      }
    }

    &.today {
      border: 2rpx solid #007aff;
    }
  }
}

.sign-btn {
  position: absolute;
  bottom: 5rpx;
  left: 50%;
  transform: translateX(-50%);
  font-size: 20rpx;
  background-color: #007aff;
  color: white;
  padding: 2rpx 15rpx;
  border-radius: 20rpx;
  margin-top: 5rpx;
}
</style>